<template>
  <div class="line-chart-card">
    <div class="card-header">
      <el-date-picker
        v-model="selectedMonth"
        type="month"
        placeholder="选择月份"
        format="YYYY-MM"
        value-format="YYYY-MM"
        @change="handleMonthChange"
      />
    </div>
    <div class="card-content">
      <div ref="chartContainer" class="chart-container"></div>
    </div>
  </div>

  <el-dialog
    destroy-on-close
    :close-on-click-modal="false"
    v-model="catInvoiceDialog"
    title="账单查询"
    width="1200"
  >
    <cat-invoice-list :filters="catInvoiceFilters"/>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts'
import type { ECharts } from 'echarts'
import { invoiceStatisticsDayOfMonthApi } from '@/api/invoice-api'
import type { ResultData } from '@/api/service'
import type { InvoiceStatisticsDayOfMonth } from '@/type/invoice-types'
import CatInvoiceList from '@/views/invoice/CatInvoiceList.vue'

// 图表实例
const chartInstance = ref<ECharts | null>(null)
const chartContainer = ref<HTMLDivElement | null>(null)

const catInvoiceDialog = ref<boolean>(false)
const catInvoiceFilters = ref<any>({})

// 日期选择
const selectedMonth = ref<string>(getCurrentMonth())

// 获取当前月份
function getCurrentMonth() {
  const now = new Date()
  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
}

// 处理月份变化
function handleMonthChange(value: string | null) {
  if (value) {
    updateChartData()
  }
}

// 初始化图表
function initChart() {
  if (chartContainer.value) {
    chartInstance.value = echarts.init(chartContainer.value)
    updateChartData()
  }
}

// 更新图表数据
function updateChartData() {
  if (!chartInstance.value) return

  invoiceStatisticsDayOfMonthApi(selectedMonth.value).then((res: ResultData<InvoiceStatisticsDayOfMonth>) => {
    const data = res.data
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'line', // 指示器类型，'line'(直线) | 'shadow'(阴影) | 'cross'(十字准星)
          label: {
            backgroundColor: '#6a7985'
          }
        },
      },
      xAxis: {
        type: 'category',
        data: data.x.map(item => `${item}日`)
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value}'
        }
      },
      series: [
        {
          data: data.y,
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          lineStyle: {
            width: 2
          },
          itemStyle: {
            color: '#409eff'
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: 'rgba(64, 158, 255, 0.3)'
                },
                {
                  offset: 1,
                  color: 'rgba(64, 158, 255, 0.05)'
                }
              ]
            }
          }
        }
      ],
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      }
    }

    chartInstance.value!.on('click', function (params) {
      // params 是事件回调函数的参数对象，包含了点击点的详细信息

      // 确保点击的是“数据项”（即折线图上的一个点）
      if (params.componentType === 'series' && params.seriesType === 'line') {
        const date = `${selectedMonth.value}-${params.name.replace("日", "")}`
        catInvoiceFilters.value.tranDatetime = {
          operator: "BETWEEN",
          value: [
            `${date} 00:00:00`,
            `${date} 23:59:59`
          ]
        }
        catInvoiceFilters.value.tranErType = {
          operator: "EQ",
          value: "支出"
        }
        catInvoiceDialog.value = true
      }
    });

    chartInstance.value!.setOption(option)

  })

}

// 监听窗口大小变化
function handleResize() {
  if (chartInstance.value) {
    chartInstance.value.resize()
  }
}

// 组件挂载时初始化
onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

// 组件卸载前清理
onBeforeUnmount(() => {
  if (chartInstance.value) {
    chartInstance.value.dispose()
  }
  window.removeEventListener('resize', handleResize)
})

// 监听月份变化
watch(selectedMonth, () => {
  updateChartData()
})
</script>

<style scoped>
.line-chart-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: end;
  align-items: center;
}

.card-content {
  flex: 1;
  padding: 0 16px 16px 16px;
  display: flex;
  flex-direction: column;
}

.chart-container {
  flex: 1;
  min-height: 200px;
}
</style>
